const mongoose = require("mongoose")

const { Schema, model } = mongoose

const UserSchema = new Schema({
  __v: {
    type: Number,
    select: false
  },
  age: {
    type: Number,
    select: false
  },
  avatar: {
    type: String
  },
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true,
    select: false
  },
  gender: {
    type: String,
    enum: ["male", "female"],
    default: "male",
    required: true
  },
  headline: {
    type: String,
    maxlength: 70
  },
  locations: {
    type: [{ type: Schema.Types.ObjectId, ref: "Topic" }],
    select: false
  },
  business: { type: Schema.Types.ObjectId, ref: "Topic", select: false },
  employments: {
    type: [
      {
        company: { type: Schema.Types.ObjectId, ref: "Topic" },
        job: { type: Schema.Types.ObjectId, ref: "Topic" }
      }
    ],
    select: false
  },
  educations: {
    type: [
      {
        school: { type: Schema.Types.ObjectId, ref: "Topic" },
        major: { type: Schema.Types.ObjectId, ref: "Topic" },
        diploma: { type: Number, enum: [1, 2, 3, 4, 5] },
        entrance_year: { type: Number },
        graduate_year: { type: Number }
      }
    ],
    select: false
  },
  personal_profile: {
    type: String,
    maxlength: 300,
    select: false
  },
  followings: {
    type: [{ type: Schema.Types.ObjectId, ref: "users" }],
    select: false
  },
  meta: {
    type: {
      createdAt: {
        type: Date,
        default: Date.now()
      },
      updatedAt: {
        type: Date,
        default: Date.now()
      }
    },
    default: {},
    select: false
  }
})

UserSchema.pre("save", function(next) {
  this.isNew && (this.meta.createdAt = this.meta.updatedAt = Date.now())
  next()
})

//  感觉这里有坑，无法拿到modal的实例进行更新
// UserSchema.pre('updateOne', function (next) {
//   console.log(5258735, this.isNew, this)
//   !this.isNew && (this.meta.updatedAt = Date.now())
//   next()
// })

const User = new model("users", UserSchema, "users")

module.exports = User
